package com.wolf.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wolf.common.exception.NoStockException;
import com.wolf.common.to.SkuHasStockTo;
import com.wolf.common.to.mq.OrderTo;
import com.wolf.common.to.mq.SeckillOrderTo;
import com.wolf.common.utils.PageUtils;
import com.wolf.common.utils.Query;
import com.wolf.common.utils.R;
import com.wolf.common.vo.MemberEntityVo;
import com.wolf.gulimall.order.constant.OrderConstant;
import com.wolf.gulimall.order.constant.PayConstant;
import com.wolf.gulimall.order.dao.OrderDao;
import com.wolf.gulimall.order.entity.OrderEntity;
import com.wolf.gulimall.order.entity.OrderItemEntity;
import com.wolf.gulimall.order.entity.PaymentInfoEntity;
import com.wolf.gulimall.order.enume.OrderStatusEnum;
import com.wolf.gulimall.order.feign.CartFeignService;
import com.wolf.gulimall.order.feign.MemberFeignService;
import com.wolf.gulimall.order.feign.ProductFeignService;
import com.wolf.gulimall.order.feign.WmsFeignService;
import com.wolf.gulimall.order.interceptor.LoginUserInterceptor;
import com.wolf.gulimall.order.service.OrderItemService;
import com.wolf.gulimall.order.service.OrderService;
import com.wolf.gulimall.order.service.PaymentInfoService;
import com.wolf.gulimall.order.to.OrderCreateTo;
import com.wolf.gulimall.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private final ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回需要的数据
     *
     * @return 所需数据
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        //使用异步编排处理远程调用,在使用异步编排的时候存在一个问题:ThreadLocal线程本地变量不能共享
        //解决:在讲主线程的本地变量数据同步到每个子线程的本地变量中去
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //获取收货地址信息
            //将主线程的本地变量数据同步到每个线程的本地变量
            RequestContextHolder.setRequestAttributes(requestAttributes);
            orderConfirmVo.setMemberAddressVos(memberFeignService.getAddress(memberEntityVo.getId()));
        }, executor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //查询购物车中的购物项信息
            //将主线程的本地变量数据同步到每个线程的本地变量
            RequestContextHolder.setRequestAttributes(requestAttributes);
            orderConfirmVo.setItems(cartFeignService.getCurrentUserCartItems());
            //feign在远程调用之前需要构造请求,会调用很多的拦截器interceptor
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIds);
            if (skuHasStock.getCode() == 0) {
                //计算结算商品是否有库存
                List<SkuHasStockTo> hasStockTos = skuHasStock.getData(new TypeReference<List<SkuHasStockTo>>() {
                });
                if (hasStockTos != null) {
                    Map<Long, Boolean> map = hasStockTos.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                    orderConfirmVo.setStocks(map);
                }
            }
        }, executor);

        //获取用户的积分信息
        orderConfirmVo.setIntegration(memberEntityVo.getIntegration());

        //设置防重令牌,防止用户多次点击造成数据问题,接口幂等性
        String token = UUID.randomUUID().toString().replace("_", "");
        //服务器保存一份token数据
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId(), token, 30, TimeUnit.MINUTES);
        //页面保存一份token数据
        orderConfirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        log.info("orderConfirmVo: {}", orderConfirmVo);
        return orderConfirmVo;
    }

    /**
     * 提交订单(下单)
     * 使用token令牌,保证接口的幂等性:
     * Token 作为 Key，用户信息作为 Value 到 Redis 中进行键值内容校验，
     * 如果 Key 存在且 Value 匹配就执行删除命令，然后正常执行后面的业务逻辑。
     * 如果不存在对应的 Key 或 Value 不匹配就返回重复执行的错误信息
     * <p>
     * Transactional 本地事务,在分布式系统中,只能控制自己的事务回滚,不能控制其它事务回滚
     * (isolation = Isolation.REPEATABLE_READ) 修改事务隔离级别:REPEATABLE_READ可重复读
     * 本地事务失效问题:
     * 同一个对象内事务方法互调默认失效,Transactional 底层是通过aop切面 动态代理通过一个代理对象来实现的
     * <p>
     * 分布式事务:
     * 产生:  1.远程服务假失败(远程服务执行成功了,但是因为网络原因没有返回)
     * 2. 远程服务调用成功,后续操作失败(当前事务能回滚,但是远程事务不能回滚)
     *
     * @param orderSubmitVo 订单信息
     * @return 提交订单返回信息
     */
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        //将参数存到线程本地变量中以便后续操作获取
        confirmVoThreadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();
        //获取当期用户
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        submitOrderResponseVo.setCode(0);
        //验证令牌[令牌验证/删除必须保证原子性,使用lua脚本]
        //脚本返回值: 0-> 令牌校验/删除失败, 1-> 令牌校验/删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        //执行lus脚本并返回
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId()), orderToken);
        if (result != null && !result.equals(0L)) {
            //验证成功,继续后续操作
            //创建订单
            OrderCreateTo order = createOrder();
            //验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //保存订单
                saveOrder(order);
                //锁定库存,只要有异常,就要回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(orderItemEntity -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(orderItemEntity.getSkuId());
                    orderItemVo.setCount(orderItemEntity.getSkuQuantity());
                    orderItemVo.setTitle(orderItemEntity.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                //远程服务锁定库存
                //库存锁定成功,因为网络原因导致远程调用超时,订单事务会回滚,库存事务不会回滚,导致一个问题:库存扣减了,没有相应的订单
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁定库存成功
                    submitOrderResponseVo.setOrder(order.getOrder());
                    //订单创建成功发送消息给rabbitmq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return submitOrderResponseVo;
                } else {
                    //锁定库存失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
//                    submitOrderResponseVo.setCode(3);
                }
            } else {
                //金额校验失败
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }

        } else {
            //令牌校验失败
            submitOrderResponseVo.setCode(1);
            return submitOrderResponseVo;
        }
    }


    /**
     * 根据订单编号查询订单信息
     *
     * @param orderSn 订单编号
     * @return 订单信息
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    /**
     * 关闭订单(30分钟未支付)
     *
     * @param orderEntity 订单信息
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前订单的最新状态
        OrderEntity order = this.getById(orderEntity.getId());
        if (Objects.equals(order.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())) {
            //修改订单状态为:已取消
            OrderEntity orderEntity1 = new OrderEntity();
            orderEntity1.setId(orderEntity.getId());
            orderEntity1.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderEntity1);
            //将关闭的订单信息发送给mq一份,用来解锁库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            try {
                //每一个消息都需要做日志记录,给数据库保存消息的详细信息,定期扫描数据库将失败的消息重新发送
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //发生网络故障等其他问题,导致消息没有发送,消息需要重新发送


            }
        }
    }

    /**
     * 根据订单编号获取支付所需信息
     *
     * @param orderSn 订单编号
     * @return 支付所需信息
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        BigDecimal totalAmount = orderEntity.getTotalAmount().setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(totalAmount.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(orderItemEntities.get(0).getSkuName());
        payVo.setBody(orderItemEntities.get(0).getSkuAttrsVals());
        return payVo;
    }

    /**
     * 查询登录用户订单详情数据
     *
     * @param params 参数
     * @return 订单详情数据
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberEntityVo.getId())
                        .orderByDesc("id")
        );

        List<OrderEntity> entities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(entities);
        return new PageUtils(page);
    }


    /**
     * 根据支付宝支付成功回调结果处理,并返回处理结果
     *
     * @param payAsyncVo 支付回调信息
     * @return 处理结果
     */
    @Override
    public String handleAliPayResult(PayAsyncVo payAsyncVo) {
        //1.保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoService.save(paymentInfoEntity);

        //2.修改订单状态信息
        String tradeStatus = payAsyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = payAsyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }

        return "success";
    }

    /**
     * 创建秒杀订单
     *
     * @param seckillOrderTo 秒杀订单信息
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal totalAmount = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(totalAmount);
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(totalAmount);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(orderItemEntity);
    }

    /**
     * 修改订单状态
     *
     * @param orderSn 订单编号
     * @param code    状态码
     */
    private void updateOrderStatus(String orderSn, Integer code, Integer payType) {

        this.baseMapper.updateOrderStatus(orderSn, code, payType);
    }


    /**
     * 创建订单
     *
     * @return 订单创建成功返回信息
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //生成订单编号,通过mybatisplus 的IdWorker 方法获取
        String orderSn = IdWorker.getTimeId();
        //1.创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //2.获取订单所有的商品详情信息
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //3.计算订单的最终价格
        computePrice(orderEntity, orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }


    /**
     * 根据订单编号构建订单基本信息
     *
     * @param orderSn 订单编号
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberEntityVo.getId());
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        if (fare.getCode() == 0) {
            FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
            });
            //设置运费信息
            orderEntity.setFreightAmount(fareVo.getFare());
            //设置收货人信息
            orderEntity.setReceiverCity(fareVo.getAddress().getCity());
            orderEntity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
            orderEntity.setReceiverName(fareVo.getAddress().getName());
            orderEntity.setReceiverPhone(fareVo.getAddress().getPhone());
            orderEntity.setReceiverPostCode(fareVo.getAddress().getPostCode());
            orderEntity.setReceiverProvince(fareVo.getAddress().getProvince());
            orderEntity.setReceiverRegion(fareVo.getAddress().getRegion());
            //设置订单状态
            orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            orderEntity.setAutoConfirmDay(7);

        }
        return orderEntity;
    }

    /**
     * 构建订单所有商品详情数据信息
     *
     * @return 订单商品详情数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后一次确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        List<OrderItemEntity> itemEntities = new ArrayList<>();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            itemEntities = currentUserCartItems.stream().map(currentUserCartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(currentUserCartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /**
     * 构建订单每个商品详情信息信息
     *
     * @param orderItemVo 订单商品信息
     * @return 订单商品详情信息
     */
    private OrderItemEntity buildOrderItem(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1.商品的spu信息
        Long skuId = orderItemVo.getSkuId();
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        if (spuInfo.getCode() == 0) {
            SpuInfoVo data = spuInfo.getData(new TypeReference<SpuInfoVo>() {
            });
            orderItemEntity.setSpuId(data.getId());
            orderItemEntity.setSpuBrand(data.getBrandId().toString());
            orderItemEntity.setSpuName(data.getSpuName());
            orderItemEntity.setCategoryId(data.getCatalogId());
        }
        //2.商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPic(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        //将一个集合已指定的字符分割成一个字符串
        String skuAttr = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        //3.优惠信息(暂时不做)
        //4.积分信息
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount().toString())).intValue());
        //5.订单商品的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单商品的实际金额
        BigDecimal totalPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //总金额-优惠券金额-促销金额-积分优惠金额 = 实际支付金额
        BigDecimal realAmount = totalPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realAmount);
        return orderItemEntity;
    }

    /**
     * 计算订单的最终价格
     *
     * @param orderEntity       订单信息
     * @param orderItemEntities 订单商品详情信息
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal totalPrice = new BigDecimal("0.0");
        BigDecimal totalCouponAmount = new BigDecimal("0.0");
        BigDecimal totalIntegrationAmount = new BigDecimal("0.0");
        BigDecimal totalPromotionAmount = new BigDecimal("0.0");
        BigDecimal totalGiftIntegration = new BigDecimal("0.0");
        BigDecimal totalGiftGrowth = new BigDecimal("0.0");
        //订单实付总金额 = 订单商品的应付金额总和 + 运费 (这里还没有加运费)
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            totalCouponAmount = totalCouponAmount.add(orderItemEntity.getCouponAmount());
            totalIntegrationAmount = totalIntegrationAmount.add(orderItemEntity.getIntegrationAmount());
            totalPromotionAmount = totalPromotionAmount.add(orderItemEntity.getPromotionAmount());
            totalPrice = totalPrice.add(orderItemEntity.getRealAmount());
            totalGiftIntegration = totalGiftIntegration.add(new BigDecimal(orderItemEntity.getGiftIntegration()));
            totalGiftGrowth = totalGiftGrowth.add(new BigDecimal(orderItemEntity.getGiftGrowth()));
        }
        //订单的总金额
        orderEntity.setTotalAmount(totalPrice);
        //订单应付金额
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(totalCouponAmount);
        orderEntity.setIntegrationAmount(totalIntegrationAmount);
        orderEntity.setPromotionAmount(totalPromotionAmount);
        //设置积分信息
        orderEntity.setGrowth(totalGiftGrowth.intValue());
        orderEntity.setIntegration(totalGiftIntegration.intValue());
        //0 -> 未删除
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 保存订单数据信息
     *
     * @param order 订单信息
     */
    private void saveOrder(OrderCreateTo order) {
        //保存订单基本信息
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        //保存订单商品详情信息
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }
}